<template>
  <div class="wkDetail">
    <div class="btnGroup">
      <el-button @click="onClose" type="warning" plain icon="Close">
        关闭
      </el-button>

      <el-button @click="rfwkDialog()" plain icon="Tickets">
        批阅记录
      </el-button>
    </div>

    <div class="title">
      作业要求
    </div>
    <div class="content">

      <p v-html="wkContent"></p>
      <div class='list'>
        <div class='item' v-for='item, index in bigFileArr' :key='index'>
          <template v-if='item.original_filename'>
            <svg class='coloricon' aria-hidden='true'>
              <use :xlink:href="'#' + getFileIcon(item.original_filename)"></use>
            </svg>
            <a :href="item.path" download>{{ giveEllipsisStr(item.original_filename, 30) }}</a>

          </template>

        </div>
      </div>
    </div>

    <div class="Review-work">
      <div class="rvTitle">
        提交作业
      </div>
      <el-form class="rvwkCon" ref='workFormRef' :model='workFormOption' :rules='WorkRules' size='large'>

        <el-form-item prop='content'>
          <PubEditor :wangEditReadOnly="wangEditReadOnly" :editContent='workFormOption.content'
            @editContentEnv='editContentEnv' @imgUrlEnv="imgUrlEnv" @videoUrlEnv="videoUrlEnv"
            placeholder='请认真填写作业内容..'>
          </PubEditor>
        </el-form-item>

        <el-form-item prop='files'>
          <OtherBigFile :isHidden="isHidden" :fileArr='workFormOption.files' ref='OtherBigFileRef'
            @fileArrChange='fileArrChange'>
          </OtherBigFile>
        </el-form-item>


        <el-form-item v-if="(route.query.s_status == -1 || route.query.s_status == 2)&&route.query.status==1">
          <div class='btngroup'>
            <el-button :disabled="wangEditReadOnly" type='primary' @click='submitForm'>
              提交
            </el-button>
            <el-button @click='resetForm'>重置</el-button>
          </div>
        </el-form-item>


      </el-form>
    </div>

  </div>


  <!-- 批阅作业弹出层 -->

  <el-dialog v-model="dialogVisible" title="批阅记录" width="700">
    <div v-if="reviewArr.length > 0">
      <!-- <div v-for="item in reviewArr" class="collItem">

        <el-tag v-if="item.status == 1" style="margin-right: 10px;" type="danger">驳回</el-tag>

        <el-tag v-if="item.status == 0" style="margin-right: 10px;" type="success">通过</el-tag>
        {{ parseTime(item.time) }}批阅

        <div>
          {{ item.content }}
        </div>
      </div> -->

       <el-collapse @change="handleChange">
          <el-collapse-item v-for="item in reviewArr" class="collItem">
            <template #title>
              <el-tag
                v-if="item.status == 1"
                style="margin-right: 10px"
                type="danger"
                >驳回</el-tag
              >

              <el-tag
                v-if="item.status == 0"
                style="margin-right: 10px"
                type="success"
                >通过</el-tag
              >
              {{ parseTime(item.time) }}批阅
            </template>
            <div v-html="item.remark">

            </div>
          </el-collapse-item>
        </el-collapse>

    </div>
    <div class='diaCon' v-else>
      <el-empty description='暂无批阅记录' />
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue"
import {
  getFileIcon,
  giveEllipsisStr,
  parseTime

} from '@/utils/common';
import PubEditor from '@/components/PubEditor/index.vue';
import { getRowWork, upStusubwk, subwork, stusubDetail, reviewRecord } from "@/api/banke/zuoye"
import OtherBigFile from '@/components/OtherBigFile/index.vue';
import { ElMessage } from 'element-plus';
const imgUrlArr = ref([])
const videoUrlArr = ref([])
const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const wkContent = ref()
const bigFileArr = ref([])
const dialogVisible = ref(false)
// 批阅记录数据
const reviewArr = ref([
])

const wangEditReadOnly = ref((route.query.s_status == -1 || route.query.s_status == 2)&&route.query.status==1 ? false : true)

const isHidden = ref((route.query.s_status == -1 || route.query.s_status == 2)&&route.query.status==1 ? true : false)
//作业表结构
const workFormOption = ref({
  operation_id: route.query.id,
  content: '',    //富文本内容
  files: []//附件
});
//表结构验证规则
const WorkRules = ref({
  content: [
    { required: true, message: '作业内容必须填写', trigger: 'blur' },
  ]

});

// 获取批阅记录
const getreviewRecord = (id) => {
  reviewRecord(id).then(res => {
    console.log(res);
    reviewArr.value = res
  })
}

const rfwkDialog = () => {

  dialogVisible.value = true
  getreviewRecord(route.query.submit_id)
}

// 获取上传图像成功的Url
const imgUrlEnv = (e) => {

  console.log(e);

  imgUrlArr.value.push(e)
}
//大附件内容改变
const fileArrChange = (e) => {
  console.log(e);
  workFormOption.value.files = e;
};

// 关闭当前页
const onClose = () => {
  proxy.$tab.closePage(route).then(res => {
    router.go(-1)
  })
}
// 获取上传视频成功的url
const videoUrlEnv = (e) => {
  videoUrlArr.value.push(e)
}
//获取富文本返回的内容
const editContentEnv = (e) => {
  if (e == '<p><br></p>') {
    e = ''
  }

  if (workFormOption.value.content) {
    proxy.$refs['workFormRef'].clearValidate(['content']);
  }

  workFormOption.value.content = e;
  // 将上传成功的图像和视频的[file_id: ${res.file_id},url: ${tem_url.value}]地址分别放在alt和poster属性中

  // 新增索引映射函数，建立匹配位置与上传文件的对应关系
const processMediaAttributes = (content, urlArr, regex, attrName) => {
  let index = 0;
  return content.replace(regex, (match) => {
    // 只替换对应序号的属性值
    if (index < urlArr.value.length) {
      const replacement = `${attrName}="${urlArr.value[index++]}"`;
      return match.replace(/(alt|poster)=".*?"/, replacement);
    }
    return match;
  });
};

// 使用示例
if (imgUrlArr.value.length > 0 || videoUrlArr.value.length > 0) {
  // 分步骤处理不同媒体类型
  // 处理图片alt属性（按上传顺序逐个替换）
  workFormOption.value.content = processMediaAttributes(
    workFormOption.value.content,
    imgUrlArr,
    /<img[^>]*alt="[^"]*"[^>]*>/g,
    "alt"
  );

  // 处理视频poster属性（按上传顺序逐个替换）
  workFormOption.value.content = processMediaAttributes(
    workFormOption.value.content,
    videoUrlArr,
    /<video[^>]*poster="[^"]*"[^>]*>/g,
    "poster"
  );
}


};


console.log(route.query.id);
// 老师布置的作业详情
const getwkDetail = (id) => {
  getRowWork(route.query.id).then(res => {
    bigFileArr.value = res.files
    wkContent.value = res.content
    console.log(res);
    wkContent.value = wkContent.value.replace(/\[file_id: (\d+),url: (.+?\.(jpg|png|webp|svg|gif).*?)\]/g, '<img src="$2" alt="[file_id: $1,url: $2]"/>');

    wkContent.value = wkContent.value.replace(/<div data-w-e-type="video" data-w-e-is-void>\s*\[file_id:\s*(\d+),url:\s*([^[\]]+)\]\s*<\/div>/g, '<video controls src="$2"></video>');

    // // 去除多余的符号
    wkContent.value=wkContent.value.replace(/>" data-href="?" style="?"\//g, '');


// 处理图像回显问题
const processString = (str) => {
  // 处理 img 标签的 src 替换为 alt 中的 url
  const processedImgStr = str.replace(/<img[^>]*alt="\[file_id:[^,]*,url: ([^"]*)"[^>]*>/g, (match, url) => {
    return match.replace(/src="[^"]*"/, `src="${url.replace(/\]/g, '')}"`);
  });

  // 处理 video 标签中的 source 标签的 src 替换为 poster 中的 url
  const processedVideoStr = processedImgStr.replace(/<video[^>]*poster="\[file_id:[^,]*,url: ([^"]*)"[^>]*>.*?<source[^>]*src="[^"]*"[^>]*>/g, (match, url) => {
    return match.replace(/<source[^>]*src="[^"]*"/, `<source src="${url.replace(/\]/g, '')}"`);
  });

  return processedVideoStr;
};

wkContent.value = processString(wkContent.value);



  })
}

// 学生提交的作业详情

const getstuwkDetail = () => {
  stusubDetail(route.query.submit_id).then(res => {
    console.log(res);


    workFormOption.value.content = res.content
    workFormOption.value.files = res.files
    // 回显图像和视频
    workFormOption.value.content = workFormOption.value.content.replace(/\[file_id: (\d+),url: (.+?\.(jpg|png|webp|svg|gif).*?)\]/g, '<img src="$2" alt="[file_id: $1,url: $2]"/>');

    workFormOption.value.content = workFormOption.value.content.replace(/<div data-w-e-type="video" data-w-e-is-void>\s*\[file_id:\s*(\d+),url:\s*([^[\]]+)\]\s*<\/div>/g, '<video poster="[file_id: $1,url: $2]" src="$2"></video>');
    // // 去除多余的符号
    workFormOption.value.content = workFormOption.value.content.replace(/>" data-href="?" style="?"\//g, '');

// 处理图像回显问题
const processString = (str) => {
  // 处理 img 标签的 src 替换为 alt 中的 url
  const processedImgStr = str.replace(/<img[^>]*alt="\[file_id:[^,]*,url: ([^"]*)"[^>]*>/g, (match, url) => {
    return match.replace(/src="[^"]*"/, `src="${url.replace(/\]/g, '')}"`);
  });

  // 处理 video 标签中的 source 标签的 src 替换为 poster 中的 url
  const processedVideoStr = processedImgStr.replace(/<video[^>]*poster="\[file_id:[^,]*,url: ([^"]*)"[^>]*>.*?<source[^>]*src="[^"]*"[^>]*>/g, (match, url) => {
    return match.replace(/<source[^>]*src="[^"]*"/, `<source src="${url.replace(/\]/g, '')}"`);
  });

  return processedVideoStr;
};

workFormOption.value.content = processString(workFormOption.value.content);
    

  })

}
// 重置作业
const resetForm = () => {

  proxy.$refs.workFormRef.resetFields()

}


// 提交作业
const submitForm = () => {


// 优化后的正则表达式（增加精准匹配和非贪婪模式）
const imgAltRegex = /<img\b(?=(?:[^>]*?\balt=(["'])(.*?)\1)?)[^>]*>/gmi;
const videoPosterRegex = /<video\b(?=(?:[^>]*?\bposter=(["'])(\[file_id:.*?])"|')?)[^>]*>.*?<\/video>/gmis;

// 调整替换顺序：先处理视频再处理图片
const processRichText = (html) => {
  // 第一阶段：处理视频标签（保留结构）
  const videoProcessed = html.replace(videoPosterRegex, (match, quote, posterJson) => {
    try {
      // 解析JSON格式的poster数据
      const [posterData] = JSON.parse(posterJson);
      return match.replace(posterJson, posterData.url); // 仅替换poster值
    } catch {
      return match; // 解析失败保持原样
    }
  });

  // 第二阶段：处理图片标签（保留结构）
  const imgProcessed = videoProcessed.replace(imgAltRegex, (match, quote, altValue) => {
    return altValue ? match.replace(altValue, altValue.trim()) : match;
  });

  return imgProcessed;
};

// 使用示例
const result = processRichText(workFormOption.value.content);
console.log('安全处理结果:', result);


  

  proxy.$refs['workFormRef'].validate(valid => {
    if (valid) {
      if (workFormOption.value.files) {
        workFormOption.value.files = workFormOption.value.files.map(item => item.file_id);
      }
      // 如果存在提交的id走更新作业,不存在走提交作业
      if (route.query.submit_id) {
        let data = {
          id: route.query.submit_id,
          content: result,
          operation_id: workFormOption.value.operation_id,
          files: workFormOption.value.files
        }
        console.log(data);

        upStusubwk(data).then(res => {
          console.log(res);
          if (!res) {
            ElMessage.success('提交成功');
            proxy.$refs.workFormRef.resetFields()
            // 关闭当前页，返回上一页
            proxy.$tab.closePage(route).then(res => {
              router.back()
            })

          } else {
            ElMessage.error(res.response.data);
          }
        })
        return
      }


      // 提交作业

      let data={
        operation_id:workFormOption.value.operation_id,
        content: result,    //富文本内容
        files:workFormOption.value.files//附件
      }
      
      subwork(data).then(res => {
        console.log(res)

        if (!res) {
          ElMessage.success('提交成功');
          // 关闭当前页，返回上一页
          proxy.$tab.closePage(route).then(res => {
            router.back()
          })
        } else {
          ElMessage.error(res.response.data);
        }
      })


    }


  })

}
getwkDetail()

if (route.query.submit_id) {
  getstuwkDetail()
}






</script>

<style lang="scss" scoped>
.title {
  height: 50px;
  background: #F8F8F9;
  line-height: 60px;
  text-align: center;
  margin: 20px 0;
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.rvTitle {
  height: 50px;
  background: #F8F8F9;
  line-height: 60px;
  text-align: center;
  margin: 50px 0 30px 0;
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.content {
  font-size: 14px;
  line-height: 1.7em;
  width: 80%;
  margin: 0 auto;
}

.Review-work {
  .rvwkCon {
    width: 80%;
    margin: 0 auto;
  }

}

.list {
  display: flex;
  flex-wrap: wrap;
  padding-top: 20px;

  .item {
    padding-right: 35px;
    display: flex;
    align-items: center;
    font-size: 15px;
    position: relative;
    margin-bottom: 10px;

    a {
      color: #666;
    }

    .coloricon {
      font-size: 25px;
      margin-right: 5px;
    }

    .close {
      font-size: 22px;
      color: #ff5733;
      position: absolute;
      right: 5px;
      top: 0px;
      display: none;
      cursor: pointer;
      line-height: 1em;
    }

    &:hover {
      .close {
        display: block;
      }
    }
  }
}

.collItem {
  line-height: 60px;
  // border-top: 1px solid #eee;

}
</style>